// web/src/app/learn/(course)/courses/[courseId]/chapters/[chapterId]/_components/course-enroll-button.tsx
'use client';
import React, {useState} from 'react';
import {formatPrice} from "@/lib/format";
import {Button} from "@/components/ui/button";
import toast from "react-hot-toast";

interface Props {
    courseId: string;
    price: number
}

const CourseEnrollButton = ({courseId, price}: Props) => {
    const [isLoading, setIsLoading] = useState(false)

    const onClick = async () => {
        try {
            setIsLoading(true)

            const response = await fetch(`/api/course/${courseId}/checkout`, {
                method: "POST",
            })
            const data = await response.json()
            if (!response.ok) throw new Error(`Failed to fetch ${await response.text()}`)
            console.log(data.url)

            window.location.assign(data.url)
        } catch (e) {
            console.error(e)
            toast.error(`Something went wrong`)
        } finally {
            setIsLoading(false)
        }
    }

    return (
        <Button
            disabled={isLoading}
            onClick={onClick}
            size={'sm'}
            className={`w-full md:w-auto`}
        >
            Enroll for {formatPrice(price)}
        </Button>
    );
};

export default CourseEnrollButton;